package com.cloneoner.video
{
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.geom.Point;

	/** Dispatched when the slices are build. */
    [Event(name="complete", type="flash.events.Event")]
	
	/**
	 * Build a vector contained bitmapdata for each frames of the MovieClip in param
	 * 
	 * @author Thibault Loup - Cloneoner.com
	 */
	public class ClSliceBuilder extends EventDispatcher
	{
		
		// __________________________________________________________
		// -										 	  CONSTRUCTOR
		/**
		 * Constructor
		 * @param pMovieClip The MovieClip to parse
		 */
		public function ClSliceBuilder(pMovieClip:MovieClip)
		{
			_mc = pMovieClip;
			_build();
		}
		
		// __________________________________________________________
		// -										  PUBLICS METHODS
		
		/** Returns the slices */
		public function getSlices() : Vector.<BitmapData>
		{
			return _slices;
		}
		
		/** Returns the frames Label */
		public function getFramesLabel() : Array
		{
			return _framesLabel;
		}
		
		/** Start build. */
		public function build():void
		{
			if( _c!= 0) return;
			
			_mc.addEventListener(Event.ENTER_FRAME, _onEnterFrame);
		}
		
		/** Dispose */
		public function dispose() : void
		{
			if( !_mc )return;
			
			_mc.removeEventListener(Event.ENTER_FRAME, _onEnterFrame);
			_mc.soundTransform.volume = 0;
			_mc.stop();
			_mc = null;
		}
		
		// __________________________________________________________
		// -										 		   EVENTS
		/** @private */
		private function _onEnterFrame(e:Event):void
		{
			var c:int = _c;
			++c;
			
			_drawFrame(c);
			
			if( c > _totalFrames)
			{
				dispose();
				dispatchEvent(new Event(Event.COMPLETE));
			}
			_c = c;
		}
		
		// __________________________________________________________
		// -										 PRIVATES METHODS
		
		/** @private */
		private function _build() : void
		{
			_slices = new Vector.<BitmapData>( _mc.totalFrames );
			_size = new Point(_mc.width, _mc.height);
			_framesLabel = _mc.currentLabels;
			_totalFrames = _mc.totalFrames;
		}
		
		/** @private */
		private function _drawFrame(pFrame:int):Boolean
		{
			if( pFrame > _totalFrames || pFrame <= 0 ) return false;
			
			var f:int = pFrame;
			_mc.gotoAndStop(f);
			var bmpd:BitmapData = new BitmapData(_size.x, _size.y, true, 0);
			bmpd.draw(_mc);
			_slices[f-1] = bmpd;
			
			return true;
		}
		
		
		/* VAR */
		private var _mc:MovieClip;
		private var _slices : Vector.<BitmapData>;
		private var _framesLabel:Array;
		private var _size:Point;
		
		private var _c:int = 1;
		private var _totalFrames:int;
	}
}